package com.experienceBaby.Cashbook.fragment;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bigkoo.pickerview.TimePickerView;
import com.experienceBaby.Cashbook.activity.EditorActivity;
import com.experienceBaby.Cashbook.R;
import com.experienceBaby.Cashbook.adapter.MyExpandableAdapter;
import com.experienceBaby.Cashbook.bean.Daily;
import com.experienceBaby.Cashbook.greendao.DbController;
import com.experienceBaby.Cashbook.utils.DateUtils;

import org.greenrobot.greendao.annotation.NotNull;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class DetailFragment extends Fragment {
    private ExpandableListView lm_elv;
    private static List<String> Group;
    private static List<List<String>> Children;
    private static View view;
    private LinearLayout ll;
    private TextView tv_income, tv_expenditure, tv_year, tv_month;
    public int year11, month11;
    public static boolean aBoolean = true;
    public static MyExpandableAdapter myExpandableAdapter;
    private static DbController dbController;
    private static int id;

    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_detail, container, false);
        dbController = new DbController(getContext());
        initView();

        return view;
    }

    private void initData(int year, int mouth) {
        Group = new ArrayList<>();
        Children = new ArrayList<>();
        DbController dbController = new DbController(view.getContext());
        final List<Daily> dailies = dbController.searchByMonth(year, mouth);
//        Log.i("initData", "" + dailies);

        for (int i = 0; i < dailies.size(); i++) {
            int Year = dailies.get(i).getDate().getYear() + 1900;
            int Month = dailies.get(i).getDate().getMonth() + 1;
            int Day = dailies.get(i).getDate().getDate();
            double cost = dailies.get(i).getCost();
            if (DateUtils.getWeekToday(Year, Month, Day) == 1) {
                Group.add(Month + "月" + Day + "日" + " 星期一" + " " + cost);
            } else if (DateUtils.getWeekToday(Year, Month, Day) == 2) {
                Group.add(Month + "月" + Day + "日" + " 星期二" + " " + cost);

            } else if (DateUtils.getWeekToday(Year, Month, Day) == 3) {
                Group.add(Month + "月" + Day + "日" + " 星期三" + " " + cost);

            } else if (DateUtils.getWeekToday(Year, Month, Day) == 4) {
                Group.add(Month + "月" + Day + "日" + " 星期四" + " " + cost);

            } else if (DateUtils.getWeekToday(Year, Month, Day) == 5) {
                Group.add(Month + "月" + Day + "日" + " 星期五" + " " + cost);

            } else if (DateUtils.getWeekToday(Year, Month, Day) == 6) {
                Group.add(Month + "月" + Day + "日" + " 星期六" + " " + cost);

            } else if (DateUtils.getWeekToday(Year, Month, Day) == 7) {
                Group.add(Month + "月" + Day + "日" + " 星期日" + " " + cost);

            }
            List<String> list = new ArrayList<>();
            for (int j = 0; j < dailies.get(i).getDatas().size(); j++) {
                String type = dailies.get(i).getDatas().get(j).getType();
                String remark = dailies.get(i).getDatas().get(j).getType();
                double cost1 = dailies.get(i).getDatas().get(j).getCost();
                if (dailies.get(i).getDatas().get(j).getIncome() == 0) {
                    list.add(type + " " + remark + " -" + cost1);
                } else {
                    list.add(type + " " + remark + " " + cost1);
                }
            }
            Children.add(list);
        }

        //ExpandableListView适配
        lm_elv = view.findViewById(R.id.lm_elv);
        myExpandableAdapter = new
                MyExpandableAdapter(view.getContext(), Group, Children);
        lm_elv.setAdapter(myExpandableAdapter);
        expandGroup();

        lm_elv.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                Intent intent = new Intent(getActivity(), EditorActivity.class);
                DetailFragment.id = Integer.parseInt(String.valueOf(dailies.get(groupPosition).getDatas().get(childPosition).getId()));
                intent.putExtra("id", DetailFragment.id);
                intent.putExtra("xx", Children.get(groupPosition).get(childPosition));
                intent.putExtra("data", Group.get(groupPosition));
                intent.putExtra("year11", year11);
                intent.putExtra("groupPosition", groupPosition);
                intent.putExtra("childPosition", childPosition);
                startActivity(intent);

//                if (!aBoolean) {
//                    Children.get(groupPosition).remove(childPosition);
//                    myExpandableAdapter.notifyDataSetChanged();
//                    aBoolean = true;
//                }

                return false;
            }
        });


//        Group.add("5月17日 星期一 支出：20");
//        Group.add("5月18日 星期二 支出：50");
//        Group.add("5月19日 星期三 支出：35");
//        for (int i = 0; i < 3; i++) {
//            List<String> list = new ArrayList<>();
//            list.add("购物 中性笔 " + Math.random() * 10);
//            list.add("餐饮 午饭 " + Math.random() * 10);
//            list.add("餐饮 晚饭 " + Math.random() * 10);
//            Children.add(list);
//        }

    }

    public static Handler handler = new Handler() {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 1:
                    dbController.delete(String.valueOf(id));
                    Children.get(msg.arg1).remove(msg.arg2);
                    myExpandableAdapter.notifyDataSetChanged();
                    Toast.makeText(view.getContext(), "删除成功", Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    DetailFragment d = new DetailFragment();
                    d.initView();
//                    myExpandableAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    private void initView() {
        Calendar now = Calendar.getInstance();
        ll = view.findViewById(R.id.ll);
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerView pvTime = new TimePickerView.Builder(view.getContext(), new TimePickerView.OnTimeSelectListener() {
                    @Override
                    @Deprecated
                    public void onTimeSelect(Date date, View v) {
                        Log.i("onTimeSelect", "" + (date.getYear() + 1900));
                        Log.i("onTimeSelect", "" + (date.getMonth() + 1));
                        year11 = date.getYear() + 1900;
                        month11 = date.getMonth() + 1;
                        tv_year.setText(year11 + "");
                        tv_month.setText(String.format("%02d", month11));
                        initData(year11, month11);
                    }
                })
                        .setType(new boolean[]{true, true, false, false, false, false})
                        .setLabel("年", "月", "", "", "", "")//默认设置为年月日时分秒
                        .setSubmitText("确定")//确定按钮文字
                        .setCancelText("取消")//取消按钮文字
                        .setTitleText("请选择")//标题
                        .setSubCalSize(18)//确定和取消文字大小
                        .setTitleSize(20)//标题文字大小
                        .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                        .isCyclic(false)//是否循环滚动
                        .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                        .setDividerColor(Color.YELLOW)//设置分割线的颜色
                        .setContentSize(21)//滚轮文字大小
                        .setLineSpacingMultiplier(1.2f)//设置两横线之间的间隔倍数
                        .setTextXOffset(-10, 0, 10, 0, 0, 0)//设置X轴倾斜角度[ -90 , 90°]
                        .setBackgroundId(0x00FFFFFF) //设置外部遮罩颜色
                        .setDecorView(null)//设置要将pickerview显示到的容器id 必须是viewgroup
                        .isDialog(false)//是否显示为对话框样式
                        .build();
                pvTime.show();


            }
        });

        //收入
        tv_income = view.findViewById(R.id.tv_income);
        //支出
        tv_expenditure = view.findViewById(R.id.tv_expenditure);

        tv_year = view.findViewById(R.id.tv_year);
        tv_year.setText(now.get(Calendar.YEAR) + "");
        year11 = now.get(Calendar.YEAR);
        tv_month = view.findViewById(R.id.tv_month);
        tv_month.setText(String.format("%02d", (now.get(Calendar.MONTH) + 1)));
        month11 = now.get(Calendar.MONTH) + 1;
        initData(year11, month11);


    }

    private void expandGroup() {
        lm_elv.setGroupIndicator(null);
        int groupCount = lm_elv.getCount();
        for (int i = 0; i < groupCount; i++) {
            lm_elv.expandGroup(i);
        }
    }


}
